<template>
  <div>
    <div class="mui-popover mui-popover-action slg-cart-confirm">
      <header id="header" class="auto-rem mui-bar mui-bar-nav">
        <a class="mui-icon mui-icon-left-nav mui-pull-left" @tap.prevent.stop="closeConfirm"></a>
        <h1 class="mui-title">
          订单确认
        </h1>
      </header>
      <div class="mui-content">
        <div id="confirmscroll" class="mui-scroll-wrapper">
          <div class="mui-scroll">
            <div v-if="Object.keys(usercontact).length > 0" class="step1" @tap.prevent.stop="chooseContact">
              <div class="step-top">
                <div class="user">收货人 : {{usercontact.name}}</div>
                <div class="phone">{{usercontact.phone}}</div>
              </div>
              <div class="step-bottom">
                {{usercontact.province}}  {{usercontact.city}}  {{usercontact.district}}  {{usercontact.address}}
              </div>
              <span class="step-location-img mui-icon mui-icon-location"></span>
              <b class="s1-borderB"></b>
            </div>
            <div v-else class="step1" @tap.prevent.stop="chooseContact">
              <h3>请添加收货地址</h3>
            </div>
            <div class="step3">
              <div class="s-item change-p1">
                <div class="sitem-l change-h1">
                  <div class="sl-img" v-for="product in confirmcarts">
                    <img :src="webApiDomain + '/public/uploads/' + product.savepath + product.savename">
                    <p>×{{product.num}}</p>
                  </div>
                </div>
                <div class="sitem-r change-m2">共{{totalnum}}件</div>
              </div>
            </div>
            <div id="mylist">
              <ul class="mui-table-view">
                <li class="mui-table-view-cell mui-collapse" style="display:none">
                  <a class="mui-navigate-right">{{ payment == 4 ? '余额支付' : '微信支付' }}</a>
                  <div class="mui-collapse-content">
                    <div>
                      <button type="button"
                              :class="payment == 4 ? 'mui-btn mui-btn-outlined mui-btn-danger' : 'mui-btn mui-btn-outlined'"
                              @tap.prevent.stop="setPayment(4)">余额支付
                      </button>
                      <button type="button"
                              :class="payment == 2 ? 'mui-btn mui-btn-outlined mui-btn-danger' : 'mui-btn mui-btn-outlined'"
                              @tap.prevent.stop="setPayment(2)">微信支付
                      </button>
                    </div>
                  </div>
                </li>
                <li class="mui-table-view-cell" style="display: none;">
                  <span style="width: 51px;display: inline-block;">积分</span>
                  <input type="text" v-if="usescore" class="table-view-input" :value="inputscore / 100"
                         @change="scoreChange($event.target)">
                  <div class="mui-switch mui-switch-mini mui-active" @toggle="scoreSwitch">
                    <div class="mui-switch-handle"></div>
                  </div>
                </li>
                <li class="mui-table-view-cell">
                  <span>现金券</span>
                  <input type="text" class="table-view-input" :value="(usercash / 100).toFixed(2)"
                         @change="cashChange($event.target)">
                  <div class="mui-switch mui-switch-mini" @toggle="cashSwitch">
                    <div class="mui-switch-handle"></div>
                  </div>
                </li>
              </ul>
            </div>
            <div class="step4">
              <div class="row">
                <span class="left">商品金额</span>
                <span class="right">￥{{(totalprice / 100).toFixed(2)}}</span>
              </div>
              <div class="row" v-if="totalscore > 0">
                <span class="left">所需积分</span>
                <span class="right">{{(totalscore / 100).toFixed(0)}} (当前可用积分：{{(userscore / 100).toFixed(0)}})</span>
              </div>
              <div class="row">
                <span class="left">可获得积分</span>
                <span class="right">{{(score / 100 * 10).toFixed(0)}}</span>
              </div>
              <div class="row" v-if="usecash">
                <span class="left">现金券抵扣</span>
                <span class="right">-￥{{(inputcash / 100).toFixed(2)}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom-nav-bar">
        <div class="left">
          <div class="left-button"></div>
          <div class="right-text">
          <span class="top-text">
            共抵扣: ￥{{discountScore}}
          </span>
            <span class="bottom-text">
            实付款:
            <span class="price">￥{{discountPrice}}</span>
          </span>
          </div>
          <span></span>
        </div>
        <div class="right" @tap.prevent.stop="orderAdd">订单提交</div>
      </div>
    </div>
    <address-manager :onSelect="handleAddressSelect"></address-manager>
    <order-detail :orderid="orderid"></order-detail>
  </div>
</template>

<script>
  import {apiDomain, ajax} from 'assets/js/Lib'
  import {mask, maskSpinner} from 'assets/js/slgMask'

  import OrderDetail from 'components/OrderDetail'
  import AddressManager from 'components/AddressManager'
  import 'assets/js/url';

  export default {
    data() {
      return {
        usescore: false,//true,
        usecash: false,
        userscore: 0,
        usermoney: 0,
        usercash: 0,
        inputscore: 0,
        inputcash: 0,
        usercontact: {},
        orderid: 0,
        payment: 4,
        score: 0,
      }
    },
    computed: {
      webApiDomain: function () {
        return apiDomain;
      },
      discountScore: function () {
//      return (((this.usecash ? this.inputcash : 0) + (this.usescore ? this.inputscore : 0)) / 100).toFixed(0)
        return ((this.usecash ? this.inputcash : 0) / 100).toFixed(2);
      },
      discountPrice: function () {
//      return ((this.totalprice - (this.usecash ? this.inputcash : 0) + this.totalscore - (this.usescore ? this.inputscore : 0)) / 100).toFixed(0);
        return ((this.totalprice - (this.usecash ? this.inputcash : 0)) / 100).toFixed(2);
      }
    },
    components: {
      OrderDetail,
      AddressManager,
    },
    watch: {
      opentime: function () {
        ajax({
          url: '/api/cart/userinfo',
          type: 'GET',
//        data: { userId: 58 },
          success: res => {
            this.userscore = res.score - res.frozen_score;
            this.inputscore = this.totalscore > this.userscore ? res.score : this.totalscore
            this.usermoney = res.money
            this.usercash = res.cash
            this.inputcash = this.totalprice > this.usercash ? res.cash : this.totalprice
            this.usercontact = res.contact
            if (this.totalscore < this.userscore) this.inputscore = this.totalscore
            if (this.totalprice < this.usercash) this.inputcash = this.totalprice
          }
        })
      },
      confirmcarts () {
        let score = 0;
        this.confirmcarts.forEach((item) => {
          console.log('item', item);
          score += item.sku.score;
        });
        this.score = score;
      }
    },
    props: {
      confirmcarts: {
        type: Array
      },
      totalnum: 0,
      totalprice: 0,
      totalscore: 0,
      opentime: 0
    },
    //实例初始化最之前，无法获取到data里的数据
    beforeCreate() {
    },
    //在挂载开始之前被调用
    beforeMount() {
    },
    //已成功挂载，相当ready()
    mounted() {
      mui('#confirmscroll').scroll({
        scrollY: true, //是否竖向滚动
        scrollX: false, //是否横向滚动
        startX: 0, //初始化时滚动至x
        startY: 0, //初始化时滚动至y
        indicators: false, //是否显示滚动条
        deceleration: 0.0006, //阻尼系数,系数越小滑动越灵敏
        bounce: true //是否启用回弹
      });

    },
    //相关操作事件
    methods: {
      closeConfirm: function () {
        let params = url('?');
        if (params && params.right_now && params.right_now == 1) {
          window.history.back();
        } else {
          mui('.slg-cart-confirm').popover('hide')
        }
      },
      setPayment(val) {
        this.payment = val;
      },
      cashSwitch: function (e) {
        this.usecash = e.detail.isActive
      },
      scoreSwitch: function (e) {
        this.usescore = e.detail.isActive
      },
      scoreChange: function (target) {
        let val = target.value
        if (val * 100 <= this.totalscore) {
          this.inputscore = val * 100
        } else {
          target.value = this.totalscore / 100
          this.inputscore = this.totalscore
          return
        }

      },
      cashChange: function (target) {
        let val = target.value
        if (val * 100 <= this.totalprice) {
          this.inputcash = val * 100
        } else {
          target.value = this.totalprice / 100
          this.inputcash = this.totalprice
          return
        }

      },
      orderAdd: function () {
        if (this.totalscore > this.userscore) {
          mui.toast('积分不足，无法购买');
        }
        mask.show()
        document.querySelector('.mui-backdrop').appendChild(maskSpinner)

        // this.orderid = 449
        // mui('.slg-order-detail').popover('show')
        // mui('.slg-cart-confirm').popover('hide')

        ajax({
          url: '/api/order/add',
          type: 'POST',
          data: {
            cart: this.confirmcarts,
            contact_id: this.usercontact.id,
            use_cash: this.inputcash,
            use_score: this.inputscore,
            payment_id: this.payment,
            remark: ''
          },
          success: res => {
            this.orderid = res.id
            mui('.slg-order-detail').popover('show')
            mui('.slg-cart-confirm').popover('hide')
          },
          error: function (res) {
            mui.toast('订单提交失败，原因：' + res);
          },
          complete: function () {
            mask.close()
          }
        })
      },
      chooseContact() {
        mui('.slg-address-manager').popover('show')
//        mui('.slg-cart-confirm').popover('hide')
      },
      handleAddressSelect(contact) {
        this.usercontact = contact;
      }
    }
  }
</script>

<style lang="less">
  input[type=text].table-view-input {
    width: 4rem;
    margin: 0;
    border: 0;
    padding: 0;
    line-height: 21px;
    height: 19px;
    margin-left: .5rem
  }

  .step4 {
    width: 100%;
    margin-top: .2rem;
    background-color: #fff;
    padding: 6px 15px;
    .row {
      overflow: hidden;
      .left {
        float: left;
      }
      .right {
        float: right;
        color: #FF0036;
      }
      span {
        line-height: 28px;
        font-size: 17px;
      }
    }
  }

  .mui-popover.mui-popover-action.slg-cart-confirm {
    width: 100%;
    height: 100%;
    border-radius: 0;
    position: fixed;
    top: 0;
    bottom: 0;
    background-color: #efeff4;
    transform: translate3d(100%, 0, 0);
    &.mui-active {
      transform: translate3d(0, 0, 0);
    }

    .mui-scroll-wrapper {
      margin: 0;
    }

    .auto-rem.mui-bar-nav.mui-bar {
      box-shadow: 0 1px 6px #ccc;
    }
  }

  .step-forward-img {
    position: absolute;
    top: 1.15rem;
    right: .4rem;
  }

  .step1 {
    width: 100%;
    position: relative;
    top: 0;
    background-color: #fff;
    padding: .2rem 0;
    overflow: hidden;

    & > div {
      width: 100%;
      line-height: .8rem;
      text-align: left;
    }

    .step-top {
      overflow: hidden;
      font-size: .4rem;
      padding: 0 .975rem;
      opacity: .8;
      .user {
        float: left;
      }
      .phone {
        float: right;
      }
    }

    .s1-borderB {
      position: absolute;
      bottom: 1px;
      left: 0;
      height: 3px;
      width: 100%;
      background: url('../assets/img/location-border.png') repeat-x;
      background-size: 80px 4px;
    }

    .step-bottom {
      padding: 0 .975rem;
      font-size: .333333333rem;
      opacity: .5;
    }

    .mui-icon {
      font-size: .5rem;
      opacity: .5;
    }

    .step-location-img {
      position: absolute;
      font-size: .5rem;
      opacity: .8;
      top: 1.05rem;
      left: .4rem;
    }
  }

  .step2 {
    width: 100%;
  }

  .step3 {
    padding-left: .3733333333rem;
    margin-top: .3rem;
    background-color: #fff;
    .sitem-l {
      width: 7rem;
      padding-right: 2.5%;
      float: left;
      text-align: center;
    }

    .sl-img {
      width: 3.125em;
      height: 3.125em;
      float: left;
      margin-right: 7px;
    }

    .step-forward-img {
      top: 1.24rem;
      font-size: .5rem;
      opacity: .5;
    }
  }

  .s-item {
    position: relative;
    padding: .5625rem .975rem .5625rem 0;
    line-height: 1.2rem;
    overflow: hidden;
  }

  .change-p1 .change-h1 {
    height: 2.21875rem;
    padding-left: 0;
    overflow: hidden;
  }

  .step3 .change-p1 .sl-img {
    height: 2.21875rem;
  }

  .sitem-l .sl-img {
    position: relative;
  }

  .step3 .sitem-r.change-m2 {
    color: #848689;
    font-size: .4rem;
    padding-top: .3rem;
  }

  .s-item .sitem-r {
    float: right;
    position: relative;
  }

  .step3 .sitem-l .sl-img img {
    max-width: 100%;
    border: 0 none;
    vertical-align: bottom;
  }

  .change-p1 .sl-img img {
    display: block;
  }

  .change-p1 .change-h1 p {
    display: block;
    line-height: .4rem;
    font-size: .4rem;
    color: #848689;
    width: 50px;
    text-align: center;
    margin-top: 6px;
  }

  #mylist .mui-table-view {
    position: relative;
    margin: 0;
    margin-top: .2rem;
    text-align: left;
    color: #333;
    border-radius: 0;
    padding-left: 0;
    list-style: none;
    background-color: #fff;

    &:before {
      top: 0;
    }
    &:before,
    &:after {
      height: 1px !important;
    }

    .mui-table-view-cell:after {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 15px;
      height: 1px;
      content: '';
      -webkit-transform: scaleY(.5);
      transform: scaleY(.5);
      background-color: #c8c7cc;
    }

    .mui-table-view-cell.mui-active {
      background-color: #ffffff;
    }
  }
</style>
